from decimal import Decimal
from django.shortcuts import render
from django_redis import get_redis_connection
# Create your views here.
from rest_framework.response import Response
from rest_framework.views import APIView
from rest_framework.generics import CreateAPIView
from goods.models import SKU
from orders.serializers import OrderSettlementSerializer, SaveOrderSerializer
from rest_framework.permissions import IsAuthenticated

class OrderSettlementView(APIView):

    def get(self, request):
        # 建立链接
        conn = get_redis_connection('cart')
        user = request.user
        # 从redis中获取数据
        sku_id_count = conn.hgetall('cart_%s'%user.id)
        # 获取选中状态数据
        cart_selected = conn.smembers('cart_selected_%s'%user.id)
        # 数据构建
        cart = {}
        for sku_id in cart_selected:
            cart[int(sku_id)] = int(sku_id_count[sku_id])



        # 查询数据对象
        sku_list = SKU.objects.filter(id__in=cart.keys())
        # 序列号返回
        for sku in sku_list:
            sku.count = cart[sku.id]
        freight = Decimal('10.00')
        ser = OrderSettlementSerializer({
            'freight': freight,
            'skus': sku_list
        })

        return Response(ser.data)


class SaveOrderView(CreateAPIView):

    serializer_class = SaveOrderSerializer
    permission_classes = [IsAuthenticated]